<?php

namespace App\Http\Controllers;

use App\Exceptions\ApiException;
use App\Http\Requests\BasicRequest;
use App\Http\Requests\SearchRequest;
use App\Http\Requests\StoreRequest;
use App\Models\ClientUser;
use App\Models\ClientUserHouse;
use App\Models\HouseDistrict;
use App\Models\ShopCategory;
use App\Models\ShopGoods;
use App\Models\ShopOrderAppraise;
use App\Models\ShopStore;
use App\Models\ShopStoreCommendType;
use App\Models\ShopStoreInfoImage;
use Illuminate\Support\Facades\DB;
use App\Models\ShopStoreClass;
use App\Models\ShopGoodsScore;
use App\Models\AdvanceImg;
use App\Http\Requests\NeighborInfoRequest;
class ConvenientController extends CommonController
{
    public function index(BasicRequest $request){
        $area = $this->getAddress($request);
        $lat = $area['lat'];
        $lng = $area['lng'];
        $village_id = $area['village_id'];
	    $return = array();
	    $return['category']=ShopStoreClass::where(['is_hot'=>1])->select('id','store_class_name as name','image')->orderBy('sort','asc')->limit(8)->get();
	    $return['images'] =AdvanceImg::where(['mobile_type'=>'convenient'])->select('type','image','remark','name','value')->orderBy('sort','asc')->limit(5)->get();
	    $return['recommend'] = ShopStoreCommendType::whereIn('id',['1','2','3'])->select('id','name','image')->get();
	    $return['store_list'] = ShopStore::where(['status'=>1])
            ->where('store_type','!=',0)
            ->when($village_id,function ($query) use ($village_id){
                $query->whereRaw("FIND_IN_SET(".$village_id.",village_ids)");
            })
            ->select(DB::raw('start_amount,shipping_amount,average_amount,store_class,id,store_name,store_logo,round(6378.138*2*asin(sqrt(pow(sin((' . $lat . '*pi()/180-lat*pi()/180)/2),2)+cos(' . $lat . '*pi()/180)*cos(lat*pi()/180)* pow(sin((' . $lng . '*pi()/180-lng*pi()/180)/2),2)))*1000) as distance'))->orderBy('distance','asc')
            ->pages()->each(function($v,$k){
                if($v->distance>1000){
                    $v->distance = (round($v->distance/1000)).'km';
                }else{
                    $v->distance .='m';
                }
                $v->store_class = ShopStoreClass::where(['id'=>$v->store_class])->value('store_class_name');
            });
	    return json_success('OK',$return);
    }
    //分类详细列表
    public function category(){
        $return =array();
        $return ['1'] = ShopStoreClass::where(['store_class_type'=>1])->select('id','store_class_name as name','store_class_type as type')->orderBy('is_hot','desc')->orderBy('sort','asc')->get();
        $return ['2'] = ShopStoreClass::where(['store_class_type'=>2])->select('id','store_class_name as name','store_class_type as type')->orderBy('is_hot','desc')->orderBy('sort','asc')->get();
        return json_success('OK',$return);
	}

	public function store_list(BasicRequest $request){
        $store_class_id = $request->input('category_id');
        $store_type = $request->input('store_type');
        $area = $this->getAddress($request);
        $lat = $area['lat'];
        $lng = $area['lng'];
        $village_id = $area['village_id'];
        $sort_type = $request->input('sort_type',2);
        $return = ShopStore::where(['status'=>1])
            ->where('store_type','!=',0)
            ->when($store_type,function ($query) use ($store_type){
                $query->where(['store_type'=>$store_type]);
            })
            ->when($village_id,function ($query) use ($village_id){
                $query->whereRaw("FIND_IN_SET(".$village_id.",village_ids)");
            })
            ->when($store_class_id,function ($query) use ($store_class_id){
                $query->where(['store_class'=>$store_class_id]);
            })->select(DB::raw('start_amount,shipping_amount,average_amount,store_class,id,store_name,store_logo,round(6378.138*2*asin(sqrt(pow(sin((' . $lat . '*pi()/180-lat*pi()/180)/2),2)+cos(' . $lat . '*pi()/180)*cos(lat*pi()/180)* pow(sin((' . $lng . '*pi()/180-lng*pi()/180)/2),2)))*1000) as distance'))
            ->when($sort_type,function($query) use ($sort_type){
                if($sort_type==1) {
                    $query->orderBy('sale_number','desc');
                }
            })->orderBy('distance','desc')
            ->pages()->each(function($v,$k){
                if($v->distance>1000){
                    $v->distance = (round($v->distance/1000)).'km';
                }else{
                    $v->distance .='m';
                }
                //店铺类型
                $v->store_class = ShopStoreClass::where(['id'=>$v->store_class])->value('store_class_name');
                //评分
                $all_score=ShopGoodsScore::where(['store_id'=>$this->store_id])->sum('score');
                $num = ShopGoodsScore::where(['store_id'=>$this->store_id])->count();
                $v->score = bcdiv($all_score,$num,1)?:0;
            });
        return json_success('OK',$return);
    }

    /**
     * 商家推荐列表
     * @param BasicRequest $request
     * @return array
     */
    public function recommend_store(BasicRequest $request){
	    $id = $request->input('id',1);
        $area = $this->getAddress($request);
        $lat = $area['lat'];
        $lng = $area['lng'];
        $village_id = $area['village_id'];
        $return = ShopStore::where(['status'=>1])
            ->where('store_type','!=',0)
            ->whereRaw('FIND_IN_SET('.$id.',recommend_type)')
            ->when($village_id,function ($query) use ($village_id){
                $query->whereRaw("FIND_IN_SET(".$village_id.",village_ids)");
            })
            ->select(DB::raw('start_amount,shipping_amount,average_amount,store_class,id,store_name,store_logo,round(6378.138*2*asin(sqrt(pow(sin((' . $lat . '*pi()/180-lat*pi()/180)/2),2)+cos(' . $lat . '*pi()/180)*cos(lat*pi()/180)* pow(sin((' . $lng . '*pi()/180-lng*pi()/180)/2),2)))*1000) as distance'))
            ->orderBy('distance','desc')
            ->pages()
            ->each(function($v,$k){
                if($v->distance>1000){
                    $v->distance = (round($v->distance/1000)).'km';
                }else{
                    $v->distance .='m';
                }
                
                //店铺类型
                $v->store_class = ShopStoreClass::where(['id'=>$v->store_class])->value('store_class_name');
                //评分
                $all_score=ShopGoodsScore::where(['store_id'=>$this->store_id])->sum('score');
                $num = ShopGoodsScore::where(['store_id'=>$this->store_id])->count();
                $v->score = bcdiv($all_score,$num,1)?:0;
            });
        return json_success('OK',$return);
    }
    public function store_detail(StoreRequest $request){
	    $store_id = $request->input('store_id');
	    $store_info = ShopStore::where(['id'=>$store_id])->first();
        $return['uid'] = $store_info->uid;
        $return['shipping_amount'] = $store_info->shipping_amount;
        $return['store_name'] =$store_info->store_name;
        $return['store_class'] = ShopStoreClass::where('id','=',$store_info->store_class)->value('store_class_name');
        $return['work_start_time'] = $store_info->work_start_time;
        $return['store_mobile'] = $store_info->store_mobile;
        $return['work_end_time'] = $store_info->work_end_time;
        $return['address'] = $store_info->address;
        $return['store_logo'] = $store_info->store_logo;
        $return['store_info'] = $store_info->store_info;
        $return['store_info_img'] = ShopStoreInfoImage::where(['store_id'=>$store_id])->select('id','image')->orderBy('sort','desc')->limit(5)->get();
        return json_success('OK',$return);
    }

    //评价列表
    public function appraise_list(StoreRequest $request){
        $store_id = $request->input('store_id');

        $return['score'] = ShopOrderAppraise::getSoreNum($store_id);
        $return['num'] = ShopOrderAppraise::where('store_id',$store_id)->count();
        $return['data'] = ShopOrderAppraise::where('store_id',$store_id)->select('score','detail','created_at','uid')->orderBy('id','desc')->pages()->each(function($v,$K){
            $user=ClientUser::where('id',$v->uid)->select('username','avatar')->first();
            $v->avatar =$user->avatar;
            $v->username = $user->username;
            unset($v->uid);
        });
        return json_success('OK',$return);
    }
    //商品列表
    public function goods_list(StoreRequest $request){
        $store_id = $request->input('store_id');
        $return=array();
        $return['category'] = ShopCategory::leftJoin('shop_goods','shop_goods.cate_id','=','shop_category.id')
            ->where('shop_goods.store_id',$store_id)
            ->where('shop_goods.status',1)
            ->select('shop_category.id','shop_category.cate_name','shop_category.cate_detail',DB::RAW('count(shop_goods.id) as num'))
            ->having('num','>',0)
            ->groupBy('shop_goods.cate_id')->orderBy('sort','asc')->get()->each(function($v,$K) use ($store_id){
                $v->goods_list = ShopGoods::where(['store_id'=>$store_id,'cate_id'=>$v->id,'status'=>1,'is_del'=>0])
                    ->select('id','cate_id','goods_name','goods_image','goods_price','stock','goods_type')
                    ->get();
            });
        $return['setting'] = ShopStore::where(['id'=>$store_id])->select('work_start_time','work_end_time','store_type','is_open','start_amount','shipping_amount')->first();
        $time = date('H:i');
        $work_start_time=date('H:i',strtotime($return['setting']->work_start_time));
        $work_end_time=date('H:i',strtotime($return['setting']->work_end_time));
        if($return['setting']->is_open!=1 || $time<$work_start_time || $time>$work_end_time){
            $return['is_open'] = 0;
        }else{
            $return['is_open'] = 1;
        }
        unset($return['setting']->is_open);
        return json_success('OK',$return);
    }

    //随机推荐商品
    public function recommend_goods(StoreRequest $request){
        $store_id = $request->input('store_id');
        $return = ShopGoods::where(['store_id'=>$store_id,'status'=>2])->select('id','goods_name','goods_image','goods_price')->get()->random(2);
        return json_success('OK',$return);
    }

    public function search(SearchRequest $request){
        $keyword = $request->input('keyword');
        $orderby = $request->input('orderby',1);
        $area = $this->getAddress($request);
        $lat = $area['lat'];
        $lng = $area['lng'];
        $village_id = $area['village_id'];

        $return=ShopStore::leftjoin('shop_goods','shop_goods.store_id','=','shop_store.id')
            ->select(DB::raw('shop_store.id,start_amount,shop_store.store_class,shipping_amount,average_amount,store_name,store_logo,round(6378.138*2*asin(sqrt(pow(sin((' . $lat . '*pi()/180-lat*pi()/180)/2),2)+cos(' . $lat . '*pi()/180)*cos(lat*pi()/180)* pow(sin((' . $lng . '*pi()/180-lng*pi()/180)/2),2)))*1000) as distance'))
            ->where('shop_goods.goods_name','like','%'.$keyword.'%')
            ->orWhere('shop_store.store_name','like','%'.$keyword.'%')
            ->where('store_type','!=',0)
            ->where('shop_goods.status','=','1')
            ->when($village_id,function ($query) use ($village_id){
                $query->whereRaw("FIND_IN_SET(".$village_id.",village_ids)");
            })
            ->when($orderby,function ($query) use ($orderby){
                switch ($orderby) {
                    case 1:
                        $query->orderBy('distance', 'desc');
                        break;
                    case 2:
                        $query->orderBy('sale_number', 'desc');
                        break;
                    case 3:
                        $query->orderBy('score', 'desc');
                        break;
                }
            })
            ->groupBy('shop_store.id')
            ->pages()->each(function($v,$k) use($keyword){
                if($v->distance>1000){
                    $v->distance = (round($v->distance/1000)).'km';
                }else{
                    $v->distance .='m';
                }
                $v->goods_list = ShopGoods::leftJoin('shop_goods_sale','shop_goods_sale.goods_id','=','shop_goods.id')
                    ->where('store_id','=',$v->id)
                    ->where('shop_goods.status','=','1')
                    ->where('shop_goods.goods_name','like','%'.$keyword.'%')
                    ->select('goods_name','goods_image','goods_price','market_price',DB::raw('sale_num+jsale_num as sale_num'))
                    ->get();
                //店铺类型
                $v->store_class = ShopStoreClass::where(['id'=>$v->store_class])->value('store_class_name');
            });
        return json_success('OK',$return);

    }

    private function getAddress(BasicRequest $request){
        $lat = $request->input('lat','45.7558589026808');
        $lng = $request->input('lng','126.61705');
        $ticket = $request->input('ticket');
        $village_id=false;
        if($ticket) {
            $this->check_login();
            $village_id = ClientUserHouse::where('uid','=', $this->uid)->orderBy('primary','desc')->value('village_id');
            if($village_id){
                $lat = HouseDistrict::where('id',$village_id)->value('lat');
                $lng = HouseDistrict::where('id',$village_id)->value('lng');
            }
        }
        return ['village_id'=>$village_id,'lat'=>$lat,'lng'=>$lng];
    }
}
